
import baseImg from '@/assets/logo.png';
let timer = null;

function showImage (el, imgSrc) {
     const img = new Image();
     img.src = imgSrc;
     img.onload = function() {
         el.src = imgSrc;
         el.isLoaded = true;
        }
}
// 创建一个监听器
let observer = new IntersectionObserver((entries)=>{
    // entries是所有被监听对象的集合
    entries.forEach(entry =>{
        if(entry.isIntersecting || entry.intersectionRatio>0){
            console.log(3333)
            // 当被监听元素到临界值且未加载图片时触发
            !entry.target.isLoaded  && showImage(entry.target,entry.target.data_src)
        }  
    })
})


export default {
    inserted (el, binding, vnode) {
        console.log(222)
        clearTimeout(timer)
        // 初始化时展示默认图片    
        el.src = baseImg;
         // 将需要加载的图片地址绑定在dom上   
         el.data_src = binding.value;
        observer.observe(el)
         // 防抖，这里在组件卸载的时候停止监听   
         const vm = vnode.context;
         timer = setTimeout(() => {
              vm.$on('hook:beforeDestroy', () => {
                  observer.disconnect();
             })
        }, 20);
    },
    // 图片更新触发
    update (el, binding) {
        console.log(1111)
        el.isLoaded = false;
        el.data_src = binding.value;
    },

};
